package cn.actoncode.boot.framework.minimax.core.client;

import cn.actoncode.boot.framework.minimax.config.MiniMaxProperties;
import cn.actoncode.boot.framework.minimax.core.bean.MiniMaxRequest;
import cn.actoncode.boot.framework.minimax.core.bean.MiniMaxResponse;
import cn.actoncode.boot.framework.minimax.core.enums.MiniMaxRoleEnum;
import cn.actoncode.boot.framework.minimax.core.utils.OkHttpUtils;
import com.alibaba.fastjson2.JSON;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.concurrent.TimeUnit;

import static cn.actoncode.boot.framework.common.exception.enums.GlobalErrorCodeConstants.*;
import static cn.actoncode.boot.framework.common.exception.util.ServiceExceptionUtil.exception;

@Slf4j
@RequiredArgsConstructor
public class MiniMaxChatClient {

    private final MiniMaxProperties miniMaxProperties;
    public MiniMaxResponse chat(MiniMaxRequest miniMaxRequest, String api) {

        String requestStr = JSON.toJSONString(miniMaxRequest);
        log.info("minimax: {}", requestStr);
        Request request = new Request.Builder()
                .url(api)
                .post(RequestBody.create(requestStr, MediaType.parse("application/json; charset=utf-8")))
                .header("Authorization", "Bearer " + miniMaxProperties.getApiKey())
                .header("Content-type", "application/json")
                .build();

        Call call = OkHttpUtils.getInstance().newCall(request);
        call.timeout().timeout(180, TimeUnit.SECONDS);
        try {
            Response response = call.execute();
            String responseBody = response.body().string();
            MiniMaxResponse miniMaxResponse = JSON.parseObject(responseBody, MiniMaxResponse.class);
            if (miniMaxResponse.getBaseResp() != null && miniMaxResponse.getBaseResp().getCode() != 0) {
                log.info("MiniMax Error: {}", miniMaxResponse.getBaseResp().getMsg());
                throw exception(MINI_MAX_AI_CHAT_ERROR);
            }
            return miniMaxResponse;
        } catch (IOException e) {
            log.info("MiniMax Error: {}", e.getMessage());
            throw exception(MINI_MAX_AI_CHAT_ERROR);
        }
    }

    public InputStream streamChat(MiniMaxRequest miniMaxRequest, String url) {
        log.info("minimax: {}", JSON.toJSONString(miniMaxRequest));
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(JSON.toJSONString(miniMaxRequest), MediaType.parse("application/json; charset=utf-8")))
                .header("Authorization", "Bearer " + miniMaxProperties.getApiKey())
                .header("Content-type", "text/event-stream")
                .build();

        Call call = OkHttpUtils.getInstance().newCall(request);
        call.timeout().timeout(180, TimeUnit.SECONDS);
        try {
            Response response = call.execute();
            return response.body().byteStream();
        } catch (IOException e) {
            log.info("MiniMax Error: {}", e.getMessage());
            throw exception(MINI_MAX_AI_CHAT_ERROR);
        }
    }

    public MiniMaxRequest buildRequest(String model, String prompt, Boolean stream, List<MiniMaxRequest.Message> messages) {

        MiniMaxRequest.Message message = new MiniMaxRequest.Message();
        message.setRole(MiniMaxRoleEnum.user.name());
        message.setContent(prompt);
        messages.add(message);
        // 构建请求
        MiniMaxRequest miniMaxRequest = new MiniMaxRequest();
        miniMaxRequest.setModel(model);
        miniMaxRequest.setStream(stream);
        miniMaxRequest.setMessages(messages);
        miniMaxRequest.setTemperature(0.95);
        miniMaxRequest.setTopP(0.7);
        return miniMaxRequest;
    }

}
